package com.oocl.crm.command.impl;

import java.lang.reflect.Method;

import com.oocl.crm.command.Command;
import com.oocl.crm.db.CrmUserStore;
import com.oocl.crm.exception.ParameterErrorException;
import com.oocl.crm.pojo.User;
import com.oocl.crm.service.BusinessService;
import com.oocl.crm.util.ReflectUtil;

/**
 * 新增 指令处理器
 * @author GANAB
 */
public class AddCommand extends Command{
	public AddCommand() {}
	
	public AddCommand(String params) {
		super(params);
	}
	
	public User createUser() throws ParameterErrorException{
		User user = null;
		if(this.getParams()!=null){
			//校验格式
			if(this.getParams().matches(BusinessService.USER_FIELDS_REGEX)){
				//正则已经能排除格式问题，直接取数据
				String[] fields = this.getParams().split(",");
				if(fields != null && fields.length > 0){
					String[] keyValues = null;
					user = new User();
					//获取自增ID
					user.setId(CrmUserStore.getInstance().getAutoId());
					for(String field : fields){
						keyValues = field.split(":");
						if(keyValues!=null && keyValues.length == 2){
							//反射设值，避免多个IF判断
							Method m;
							try {
								m = user.getClass().getMethod(ReflectUtil.getSetterMethodName(keyValues[0]), String.class);
								m.invoke(user, keyValues[1]);
							} catch (Exception e) {
								throw new ParameterErrorException("Add user exception: reflect failure!");
							} 
						}
					}
					if(user!=null){
						return user;
					}
				}
			}
		}
		throw new ParameterErrorException("Add user exception: parameter does not conform to the format! ");
	}
}
